﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;

namespace DNA.Mvc.jQuery
{
    public class ClientDetailView
    {
        private Dictionary<string, string> routeValues = new Dictionary<string, string>();

        public Dictionary<string, string> RouteValues
        {
            get { return routeValues; }
        }

        public string Url { get; set; }

        public string GetClientRequestUrl()
        { 
            var args=new List<string>();
            foreach (string key in routeValues.Keys)
                args.Add(key+"=" + routeValues[key]);
            string _params= string.Join("&", args.ToArray());
            if (Url.Contains("?"))
                return Url + "&" + _params;
            else
                return Url + "?" + _params;
        }
    }

    public class ClientDetailViewBuilder<TModel>
        where TModel:class
    {
        private ClientDetailView detailView;

        public ClientDetailViewBuilder(ClientDetailView view)
        {
            detailView = view;
        }

        public ClientDetailViewBuilder<TModel> Url(string url)
        {
            detailView.Url = url;
            return this;
        }
        
        public ClientDetailViewBuilder<TModel> AddRouteValue<TValue>(Expression<Func<TModel, TValue>> expression)
        {
            return this.AddRouteValue(expression, "");
        }

        public ClientDetailViewBuilder<TModel> AddRouteValue<TValue>(Expression<Func<TModel, TValue>> expression,string key)
        {
            ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, new ViewDataDictionary<TModel>());
            detailView.RouteValues.Add(!string.IsNullOrEmpty(key) ? key : modelMetadata.PropertyName, "${"+modelMetadata.PropertyName+"}");
            return this;
        }
    }
}
